var consts = require('../../../util/consts');

module.exports = function (app) { return new Handler(app); };
var Handler = function (app) { this.app = app; };
var handler = Handler.prototype;

handler.entry = function (msg, session, next) {
	var uid = msg.uid;
	var self = this;
	const ip = session.__session__.__socket__.remoteAddress.ip;

	// 判断uid是否为空
	if (!uid) {
		next(null, {
			code: consts.Code.ERR,
			msg: consts.Msg.MISSING_PARAMETER
		});
		return;
  }
	self.app.get('sessionService').kick(uid, function (err, data) {
		if (err){
			next(null, {
				code: consts.Code.ERR,
				msg: err
			});
			return
		}

		session.bind(uid);
		session.set('uid', uid);
		session.set('ip', ip);
		session.on('closed', onUserLeave.bind(null, self.app));
		session.pushAll();

		next(null, {
			code: consts.Code.SUC
		});
	});
};

var onUserLeave = function(app, session) {
	if(!session || !session.uid) {
		return;
	}
	// console.log("onUserLeave");
	app.rpc.login.loginRemote.userLeave(session, session.uid, session.frontendId, function (err) {
		console.log('userLeave uid = ' + session.uid);
		if(!!err){
			console.log('user leave error! ' + err);
		}
	});
};
